package com.hzcc.hzccblog.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzcc.hzccblog.common.Result;
import com.hzcc.hzccblog.common.ResultCodeEnum;
import com.hzcc.hzccblog.common.enums.LoginEnums;
import com.hzcc.hzccblog.common.enums.PublicEnums;
import com.hzcc.hzccblog.module.dao.UserDao;
import com.hzcc.hzccblog.module.entity.po.User;
import com.hzcc.hzccblog.module.service.MsmService;
import com.hzcc.hzccblog.utils.CodeUtil;
import com.hzcc.hzccblog.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.regex.Pattern;

import static com.hzcc.hzccblog.common.Constant.EMAIL_REX;
import static com.hzcc.hzccblog.common.Constant.REGISTER_CODE;

/**
 * @Author 早睡蛋
 * @Date 2022/7/11 21:19:20
 * @Desc:
 */
@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    private UserDao userDao;
    @Resource
    RedisUtil redisUtil;

    public final static Long msmExp = 60L;
    public final static String emailSender = "858162638@qq.com";

    @Override
    public Result sendEmail(String email) {
        String rexEmail = EMAIL_REX;
        boolean matches = Pattern.matches(rexEmail, email);
        if (!matches){
            return LoginEnums.EMAIL_REX.getResult();
        }
        QueryWrapper<User> findByUserEmail = new QueryWrapper<>();
        findByUserEmail.select("user_email").eq("user_email",email);
        User user = userDao.selectOne(findByUserEmail);
        if (user!=null){
            return LoginEnums.EMAIL_EXIST.getResult();
        }
        String isEmail = redisUtil.getString(REGISTER_CODE + email);
        if (isEmail!=null){
            return LoginEnums.MSM_EXIST.getResult();
        }
        String code = CodeUtil.getCode();
        redisUtil.setStringExpire(REGISTER_CODE + email, code, msmExp);
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("验证码");
        simpleMailMessage.setText("尊敬的用户，您的邮箱注册验证码为：   "+code+"     有效期为2分钟");
        simpleMailMessage.setTo(email);
        simpleMailMessage.setFrom(emailSender);
        javaMailSender.send(simpleMailMessage);
        return PublicEnums.OK.getResult();
    }
}
